﻿//Restriction Module v 1.0
//Written by Bugra POSTACI (c)
//August 2010

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace RestrictionModuleApp
{
    [Serializable,XmlRoot(ElementName="RestrictionRules") ]
    public class RestrictionRuleCollection:List<RestrictionRule>
    {
        public RestrictionRuleCollection()
        {
            
        }
        /// <summary>
        /// Load rules from xml file
        /// </summary>
        /// <returns>Returns RestrictionRuleCollection</returns>
        public static RestrictionRuleCollection LoadRules()
        {
            FileStream fs = null; 
            try
            {
                string path = HttpContext.Current.Server.MapPath( @"\" + RestrictionModule.ConfigFile);


                XmlSerializer xs = new XmlSerializer(typeof(RestrictionRuleCollection));
                 fs = new FileStream(path, FileMode.Open);
                XmlReaderSettings settings = new XmlReaderSettings();


                XmlReader reader = XmlReader.Create(fs, settings);
                RestrictionRuleCollection col = (RestrictionRuleCollection)xs.Deserialize(reader);
                reader.Close();
                return col;
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                fs.Close(); 
            }
        }
        /// <summary>
        /// Save rule to xml file
        /// </summary>
        /// <param name="col">Gets RestrictionRuleCollection as parameter</param>
        public static void SaveRules(RestrictionRuleCollection col)
        {
            string path = HttpContext.Current.Server.MapPath( @"\" + RestrictionModule.ConfigFile);

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            XmlTextWriter wr = new XmlTextWriter(fs, System.Text.Encoding.UTF8);
            wr.Formatting = Formatting.Indented;
            XmlSerializer xs = new XmlSerializer(typeof(RestrictionRuleCollection));
            xs.Serialize(wr, col);
            wr.Flush();
            wr.Close();


        }
    }
}